package com.qhy.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.qhy.springcloud.api.Dept;
import com.qhy.springcloud.dao.CommonResult;
import com.qhy.springcloud.service.DeptClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

/**
 * @author qiuhongyu
 * @date 2020/9/25 18:25
 */
@RestController
public class DeptController {
    private static final String HOST_URL_PREXY = "http://springcloud-provider-sentinel";

    @Autowired
    private RestTemplate restTemplatel;

    /**
     * 根据部门id查询部门信息
     *
     * @param id
     * @return
     */
    @GetMapping("/queryDept/{id}")
//    @SentinelResource(value = "queryDepts", fallback = "qhyFallback")
    @SentinelResource(value = "queryDepts", blockHandler = "qhyBlockHandle")
    public CommonResult<?> queryDept(@PathVariable("id") Long id) {
        if (id == 8) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
        }
        String url = HOST_URL_PREXY + "/queryDept/" + id;
        System.out.println(url);
        Dept dept = restTemplatel.getForObject(url, Dept.class);
        if (dept == null) {
            throw new NullPointerException("NullPointerException,所查询的数据不存在！");
        }

        return new CommonResult(200, "查询成功", dept);
    }


    public CommonResult<?> qhyBlockHandle(@PathVariable("id") Long id, BlockException blockException) {
        return new CommonResult<Object>(445, "blockHandle-限流", blockException.getMessage());

    }

    public CommonResult<?> qhyFallback(@PathVariable("id") Long id, Throwable e) {
        return new CommonResult(444, "兜底异常内容" + e.getMessage());
    }

    //==============================open=======================================
    @Autowired
    private DeptClientService deptClientService;

    @GetMapping("/queryDept/openfeign/{id}")
    public CommonResult<?> queryDeptById(@PathVariable("id") Long id) {
        CommonResult<?> commonResult = deptClientService.queryDeptById(id);

        return commonResult;
    }


}
